#include "tclientserver.h"
#include "inicpp.hpp"



TClientServer::TClientServer(QObject* parent)
    : QObject(parent)
    , m_pSocket(new QTcpSocket(this))
{
    inicpp::IniManager ini("D:/实习日志/internship-logss/TCP/TClient/x64/Debug/TClient.ini");
    QString port = QString::fromStdString(ini["Network"]["serverPort"]);
    QString IP = QString::fromStdString(ini["Network"]["serverAddress"]);
    m_pSocket->connectToHost(IP, port.toUShort());
    connect(m_pSocket, &QTcpSocket::readyRead, this, &TClientServer::onSocketReadyRead);
    
}

void TClientServer::onSocketReadyRead()
{
    auto socket = static_cast<QTcpSocket*>(sender());
    auto byteArray = socket->readAll();
    qDebug() << byteArray;
    parseByteArrayPackets(byteArray);
}


void TClientServer::parseByteArrayPackets(QByteArray byteArray)
{
    static QByteArray data;
    static bool flag = true;//标识为报文头
    static qint64 len;
    data += byteArray;

    if (data.size() < 8)
        return;
    if (flag)
    {
        flag = false;
        QDataStream ds(data);
        ds >> len;
    }

    if (data.size() < len)//数据包不完整
        return;

    else if (data.size() == len)//数据包刚好完整
    {
        flag = true;
        takeAction(data.mid(8));
        data.clear();
    }
    else if (data.size() > len)//多读取了下一个报文的数据包
    {
        takeAction(data.left(len).mid(8));
        auto temp = data.mid(len);
        data.clear();
        flag = true;
        parseByteArrayPackets(temp);//递归合并
    }

}



TClientServer* TClientServer::Instance()
{
    static TClientServer instance;
    return &instance;
}

void TClientServer::takeAction(QByteArray byteArray)
{
    QDataStream ds(byteArray);
    ds.setByteOrder(QDataStream::BigEndian);
    OPERATOR type;
    ds >> type;
    switch (type)
    {
    case OPERATOR::SEND_MESSAGE:    receiveMessage(byteArray);      break;
    }
}

void TClientServer::receiveMessage(const QByteArray& byteArray)
{
    OPERATOR Type;
    QByteArray data;
    QDataStream ds(byteArray);
    ds >> Type >> data;
    qDebug() <<"------------------" << QString::fromUtf8(data);
}

TClientServer::~TClientServer()
{}
